package com.xigege.netty.nettyComponent.eventLoopAndEventLoopGroup;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author huangxi
 * @class EventLoopServer
 * @description EventLoopServer
 * @create 2022-08-19 18:28
 */
public class EventLoopServer {
    public static void main(String[] args) {
        // worker将读写事件接受之后，创建一个defaultEventLoopGroup，专门用来处理这些事件
        // 接受读写事件由 nio 工人（NioEventLoopGroup）执行，而我们自己的 handler 由非 nio 工人（defaultEventLoopGroup）执行
        EventLoopGroup defaultEventLoopGroup = new DefaultEventLoopGroup(2);
        new ServerBootstrap()
                // boss worker
                // boss负责 ServerSocketChannel 上的 accept 事件，worker负责 SocketChannel 上的读写
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(Thread.currentThread().getName() + ": 开始处理任务");
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                                ctx.fireChannelRead(msg); // 让消息传递给下一个handler
                            }
                        }).addLast(defaultEventLoopGroup, "handle2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(Thread.currentThread().getName() + ": 开始处理任务");
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                }).bind(6666);
    }
}
